<?php 
namespace app\system\admin;
use app\system\admin\Admin;
use think\Db;
use app\system\model\Orders as OrdersModel;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use lib\Refund_pub;
/**
 *  @author Lin
 *  @time 2021/7/22
 */
class Datas extends Admin
{
    protected function initialize()
    {
        parent::initialize();
        set_time_limit(0);
        
    }

    function index(){
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $keyword = input('keyword');
            $bg_time = input('bg_time');
            $ed_time = input('ed_time');
            // echo $type."|".$bg_time."|".$ed_time;exit;
            if($bg_time){
                $bg_time = strtotime($bg_time);
                $where[] = ['pay_time','gt',$bg_time];
                $bwhere[] = ['pay_time','gt',$bg_time];
                
            }
            if($ed_time){
                $ed_time = strtotime($ed_time);
                $where[] = ['pay_time','lt',$ed_time];
                $bwhere[] = ['pay_time','lt',$ed_time];
            }
            $where[] = ['pay_status','eq',1];
            
            $is_pay_num = Db::name('orders')->where($where)->count('id');
            
            $is_pay_money = Db::name('orders')->where($where)->sum('order_price');

            $pay_man_num = Db::name('orders')->where($where)->group('uid')->count('id');

            $where[] = ['is_send','eq',0];
            $not_send_num = Db::name('orders')->where($where)->count('id');

            $bwhere[] = ['pay_status','eq',1];
            $bwhere[] = ['is_refund','eq',1];
            $refund_num = Db::name('orders')->where($bwhere)->count('id');
            // if($keyword){
            //     $where[] = ['orders_id','like',"%".$keyword."%"];
            //     // $where[] = ['name','like',"%".$keyword."%"];
            // }
            $list[] = array('is_pay_num'=>$is_pay_num,'is_pay_money'=>$is_pay_money,'pay_man_num'=>$pay_man_num,'not_send_num'=>$not_send_num,'refund_num'=>$refund_num);
            // $list = OrdersModel::where($where)->page($page)->limit($limit)->order('ctime desc')->select();
            


            $data['data'] = $list;
            // $data['count'] = OrdersModel::where($where)->count('id');
            $data['count'] = 1;
            $data['code'] = 0;
            
            return json($data);

        }
        return $this->fetch();
    }

    public function topSell(){
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $keyword = input('keyword');
            $bg_time = input('bg_time');
            $ed_time = input('ed_time');
            // echo $type."|".$bg_time."|".$ed_time;exit;
            if($bg_time){
                $bg_time = strtotime($bg_time);
                $where[] = ['ctime','gt',$bg_time];
                
            }
            if($ed_time){
                $ed_time = strtotime($ed_time);
                $where[] = ['ctime','lt',$ed_time];
            }
            
            $list = Db::name('product_sell_record')->where($where)->field("gid,sum(sell_num) as all_sell_num,sum(sell_money) as all_sell_money")->group('gid')->order('all_sell_num desc,all_sell_money desc')->limit(5)->select();

            if($list){
                $i = 1;
                foreach($list as &$value){
                    $pinfo = Db::name('product')->where('id',$value['gid'])->field('name,share_img')->find();
                    $value['name'] = $pinfo['name'];
                    $value['img'] = $pinfo['share_img'];
                    $value['pai'] = $i;
                    $i++;
                }
            }
            
            // $list[] = array('is_pay_num'=>$is_pay_num,'is_pay_money'=>$is_pay_money,'pay_man_num'=>$pay_man_num,'not_send_num'=>$not_send_num,'refund_num'=>$refund_num);
            // $list = OrdersModel::where($where)->page($page)->limit($limit)->order('ctime desc')->select();
            


            $data['data'] = $list;
            // $data['count'] = OrdersModel::where($where)->count('id');
            $data['count'] = 5;
            $data['code'] = 0;
            
            return json($data);

        }
        return $this->fetch();
    }


    public function analysis(){
        if ($this->request->isAjax()) {
            $bg_time = input('bg_time');
            $ed_time = input('ed_time');
            // echo $type."|".$bg_time."|".$ed_time;exit;
            if($bg_time){
                $bg_time = strtotime($bg_time);
                $where[] = ['pay_time','gt',$bg_time];
                $bwhere[] = ['pay_time','gt',$bg_time];
                
            }
            if($ed_time){
                $ed_time = strtotime($ed_time);
                $where[] = ['pay_time','lt',$ed_time];
                $bwhere[] = ['pay_time','lt',$ed_time];
            }
            $where[] = ['pay_status','eq',1];
            
            $is_pay_num = Db::name('orders')->where($where)->count('id');
            
            $is_pay_money = Db::name('orders')->where($where)->sum('order_price');

            $pay_man_num = Db::name('orders')->where($where)->group('uid')->count('id');

            $where[] = ['is_send','eq',0];
            $not_send_num = Db::name('orders')->where($where)->count('id');

            $bwhere[] = ['pay_status','eq',1];
            $bwhere[] = ['is_refund','eq',1];
            $refund_num = Db::name('orders')->where($bwhere)->count('id');
            // if($keyword){
            //     $where[] = ['orders_id','like',"%".$keyword."%"];
            //     // $where[] = ['name','like',"%".$keyword."%"];
            // }
            $formData[] = array('is_pay_num'=>$is_pay_num,'is_pay_money'=>$is_pay_money,'pay_man_num'=>$pay_man_num,'not_send_num'=>$not_send_num,'refund_num'=>$refund_num);


            
            $res['code']  = 0;
            $res['count'] = 0;
            $res['msg']   = "";
            $res['data']  = $formData;
            return json($res);
        }
        // $formData = Db::name("company_info")->where("id",$id)->find();
        
        return $this->fetch();
    }

    public function sendGoods(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            $id = $list['id'];

            $order_info = Db::name('orders')->where('id',$id)->find();
            $openid = Db::name('user')->where('id',$order_info['uid'])->value('openid');

            $seller_id = $list['seller_id'];
            $seller_info = Db::name('company_info')->where('id',$seller_id)->find();
            if(!$seller_info){
                return $this->error('请选择卖家物流信息模板');
            }

            $goods_id = $order_info['goods_id'];
            $goods_num = $order_info['goods_num'];
            $goods_id_arr = explode(',',$goods_id);
            $goods_num_arr = explode(',',$goods_num);
            $detail_list = array();
            foreach($goods_id_arr as $k=>$v){
                $name = Db::name('product')->where('id',$v)->value('name');
                $detail_list[] = array('name'=>$name,'count'=>$goods_num_arr[$k]);
            }

            $shop =array();
            // 只购买了单件商品
            if(count($goods_id_arr)==1){
                $goods_info = Db::name('product')->where('id',$goods_id)->find();
                $shop = array(
                    'wxa_path'=>'/pages/order/order?tab=2',//商家小程序的路径，建议为订单页面
                    'img_url'=>'https://hsq.jiwalgt.com'.$goods_info['share_img'],//商品缩略图 url；shop.detail_list为空则必传，shop.detail_list非空可不传。
                    'goods_name'=>$goods_info['name'],//商品名称, 不超过128字节；shop.detail_list为空则必传，shop.detail_list非空可不传
                    'goods_count'=>$goods_num,//商品数量；shop.detail_list为空则必传。shop.detail_list非空可不传，默认取shop.detail_list的size
                );
            }
            else{
                $detail_list1 = array();
                foreach($goods_id_arr as $k=>$v){
                    $product = Db::name('product')->where('id',$v)->field('name,sub_name,share_img')->find();
                    $detail_list1[] = array(
                        'goods_name'=>$product['name'],
                        'goods_img_url'=>'https://hsq.jiwalgt.com'.$product['share_img'],
                        'goods_desc'=>$product['sub_name']
                    );
                }

                $shop = array(
                    'wxa_path'=>'/pages/order/order?tab=2',//商家小程序的路径，建议为订单页面
                    'detail_list'=>$detail_list1
                );
            }

            $data = array(
                'add_source'=>0,
                'wx_appid'=>config('APPID'),
                'order_id'=>$order_info['orders_id'],
                'openid'=>$openid,
                // 'delivery_id'=>$list['delivery_id'],
                'delivery_id'=>'TEST',
                // 'biz_id'=>config('biz_id'),
                'biz_id'=>'test_biz_id',
                'custom_remark'=>$list['custom_remark'],
                'sender'=>array(
                    'name'=>$seller_info['name'],
                    'mobile'=>$seller_info['mobile'],
                    'province'=>$seller_info['province'],
                    'city'=>$seller_info['city'],
                    'area'=>$seller_info['area'],
                    'address'=>$seller_info['address'],
                    'company'=>$seller_info['company'],
                ),
                'receiver'=>array(
                    'name'=>$order_info['name'],
                    'mobile'=>$order_info['phone'],
                    'province'=>$order_info['province'],
                    'city'=>$order_info['city'],
                    'area'=>$order_info['district'],
                    'address'=>$order_info['address'],
                ),
                'cargo'=>array(
                    'count'=>$list['count'],//包裹数量
                    'weight'=>$list['weight'],//重量单位是千克(kg)
                    'space_x'=>$list['space_x'],//长度单位厘米(cm)
                    'space_y'=>$list['space_y'],//宽度，单位厘米(cm)
                    'space_z'=>$list['space_z'],//高度，单位厘米(cm)
                    'detail_list'=>$detail_list,
                ),
                // 保价信息
                'shop'=>$shop,
                'insured'=>array(
                    'use_insured'=>0,//是否保价，0 表示不保价，1 表示保价
                    'insured_value'=>0,//保价金额，单位是分，比如: 10000 表示 100 元（注：如果不保价，那保价金额填 0 即可）
                ),
                'service'=>array(
                    // 'service_type'=>0,//服务类型ID，详见已经支持的快递公司基本信息
                    // 'service_name'=>'标准快件',//服务名称，详见已经支持的快递公司基本信息
                    'service_type'=>1,//服务类型ID，详见已经支持的快递公司基本信息
                    'service_name'=>'test_service_name',//服务名称，详见已经支持的快递公司基本信息
                ),
                'expect_time'=>time(),
            );
            file_put_contents('a1.txt',json_encode($data,JSON_UNESCAPED_UNICODE));
            $access_token = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/express/business/order/add?access_token=".$access_token;
            $rs = juhecurl($url,json_encode($data,JSON_UNESCAPED_UNICODE),true);
            // file_put_contents('a2.txt',$rs);
            $res = json_decode($rs,true);
            if($res['errcode']==0&&$res['errmsg']=='ok'){
                Db::name('orders')->where('id',$order_info['id'])->update(array('waybill_id'=>$res['waybill_id'],'delivery_id'=>$list['delivery_id'],'is_send'=>1,'send_time'=>time(),'waybill_data_key'=>$res['waybill_data'][0]['key'],'waybill_data_value'=>$res['waybill_data'][0]['value']));
                return $this->success('发货成功');
            }
            else{
                return $this->error($rs);
            }
            
            // var_dump($rs);exit;
        }
        $id = input("id/d");
        $formData = Db::name('orders')->where('id',$id)->find();

        $goods_id_arr = explode(',',$formData['goods_id']);
        $goods_spec_arr = explode(',',$formData['goods_spec']);
        $goods_price_arr = explode(',',$formData['goods_price']);
        $goods_num_arr = explode(',',$formData['goods_num']);
        $i = 0;
        $goods_detail = '';
        foreach($goods_id_arr as $k=>&$v){
            $ginfo = Db::name('product')->where('id',$v)->field('name,share_img')->find();
            $goods_detail .= "产品名：".$ginfo['name']."--规格：".$goods_spec_arr[$k]."--数量：".$goods_num_arr[$k]."<br />";
            $i++;
        }
        $this->assign('goods_detail', $goods_detail);
        $this->assign('formData', $formData);

        // $access_token = $this->getAccessToken();
        // $url = "https://api.weixin.qq.com/cgi-bin/express/business/delivery/getall?access_token=".$access_token;
        // $rs = file_get_contents($url);
        // $wuliu = json_decode($rs,true);
        // $wuliu_list = $wuliu['data'];
        $wuliu_list[] = array(
            'delivery_id'=>'ZTO',
            'delivery_name'=>'中通快递'
        );
        $options = '';
        foreach($wuliu_list as $key=>&$value){
            $options .= "<option value='".$value['delivery_id']."'>".$value['delivery_name']."</option>";
        }
        $this->assign('options', $options);

        // 卖家信息
        $seller_info = Db::name('company_info')->select();
        if(!$seller_info){
            $this->error('请先添加卖家物流信息模板','orders/company_data','',2);
            // $this->redirect('orders/company_data')
        }
        $seller_options = '';
        foreach($seller_info as $kk=>&$vv){
            $seller_options .= "<option value='".$vv['id']."'>".$vv['beizhu']."</option>";
        }
        $this->assign('seller_options', $seller_options);

        $template = $this->request->param('template', 'send_goods');
        return $this->fetch($template);
    }

    //获取
	function getAccessToken(){
        $token_info = Db::name('access_token')->where('id',1)->find();
        if($token_info['access_token']&&time()-$token_info['ctime']<7000){
            return $token_info['access_token'];
        }
        else
        {	
            $appid=config('APPID');
            $appserct=config('APPSECRET');
            if(empty($appid)||empty($appserct)){
                return false;
            }
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appserct}";
            $getjson=file_get_contents($url);
            $getdata=json_decode($getjson,true);
            $rt=$getdata['access_token'];
            $time = time();
            if(!$token_info){
                $rs = Db::name('access_token')->insert(array('access_token'=>$rt,'ctime'=>$time));
            }
            else{
                $up_data['access_token'] = $rt;
                $up_data['ctime'] = $time;
                $rs = Db::name('access_token')->where('id',1)->update($up_data);
            }
            if($rs){
                return $rt;
            }
            else{
                return false;
            }
            
        }
      
    }

    
    function company_data(){
        if ($this->request->isAjax()) {

            $where      = [];

            $list = Db::name('company_info')->select();
            foreach($list as &$value){
                if($value['ctime']){
                    $value['ctime'] = date("Y-m-d H:i:s",$value['ctime']);
                }
                else{
                    $value['ctime'] = '';
                }
            }
            $data['data'] = $list;
            $data['count'] = Db::name('company_info')->where($where)->count('id');
            $data['code'] = 0;
            
            return json($data);

        }
        return $this->fetch();
    }

    function add(){
        if($this->request->isPost()){
            $list = $this->request->post();
            
            $list['ctime'] = time();
            $rs = Db::name("company_info")->insert($list);
            // var_dump($list);
            // return $this->error($rs);
            if($rs){
                return $this->success('添加成功');
            }
            else{
                return $this->error('添加失败，请重试');
            }
        }
        else{
            $template = $this->request->param('template', 'company_form');
            return $this->fetch($template);
        }
    }

    function edit(){
        if ($this->request->isPost()) {// 数据验证
            $list = $this->request->post();
            // var_dump($list);exit;
            $list['ctime'] = time();
            if(!$list['id']){
                return $this->error('参数错误');
            }
            else{
                $id = $list['id'];
                unset($list['id']);
                $rs = Db::name("company_info")->where('id',$id)->update($list);
                // var_dump($list);
                // return $this->error($rs);
                if($rs){
                    return $this->success('修改成功');
                }
                else{
                    return $this->error('修改失败，请重试');
                }
            }
        }
        $id = input("id/d");
        $formData = Db::name("company_info")->where("id",$id)->find();
        $this->assign('formData', $formData);
        $template = $this->request->param('template', 'company_form');
        return $this->fetch($template);
    }

    function del(){
        $id = input('id/d');
        $rs = Db::name('company_info')->where('id',$id)->delete();
        if($rs){
            return $this->success('删除成功');
        }
        else{
            return $this->error('删除失败，请重试');
        }
    }

    function refund(){
        $id = input('id/d');
        $order_info = Db::name('orders')->where('id',$id)->find();
        if(!$order_info){
            return $this->error('无订单信息');
        }
        if($order_info['is_refund']==0){
            return $this->error('用户无申请退款');
        }
        if($order_info['refund_status']==1){
            return $this->error('已退款给用户，请勿重复操作');
        }

        $param = array(
            'appid'=> config('APPID'),
            'mch_id'=> config('WX_MCH_ID'),
            'nonce_str'=> $this->createNoncestr(),
            'out_refund_no'=> $order_info['orders_id'],
            'transaction_id'=> $order_info['transaction_id'],//微信订单号
            'total_fee'=> intval($order_info['order_price']*100),
            'refund_fee'=> intval($order_info['order_price']*100),
        );
        file_put_contents('aa.txt',json_encode($param));
        $param['sign'] = $this->getSign($param);
        $xmldata = $this->arrayToXml($param);
        $xmlresult = $this->postXmlSSLCurl($xmldata,'https://api.mch.weixin.qq.com/secapi/pay/refund');
        $result = $this->xmlToArray($xmlresult);
        if($result['return_code']=='SUCCESS'&&$result['return_msg']=='OK'){
            return $this->success('退款成功');
        }
        else{
            return $this->error($result['return_msg']);
        }
        // echo ROOT_PATH;exit;
        // echo realpath('/extend/wxpay/cert/apiclient_cert.pem');exit;
        // var_dump($result);exit;
        // $result = $this->xmlToArray($xmlresult);

    }

    /*
    * 对要发送到微信统一下单接口的数据进行签名
    */
    public function getSign($Obj){
        foreach ($Obj as $k => $v){
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在string后加入KEY
        $String = $String."&key=".config('PKey');
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        return $result_;
    }
    
    /*
    *排序并格式化参数方法，签名时需要使用
    */
    public function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = "";
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }
 
    /*
    * 生成随机字符串方法
    */
    public function createNoncestr($length = 32 ){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ ) {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
    //数组转字符串方法
    public function arrayToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
    
    public function xmlToArray($xml){
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }
    
    //需要使用证书的请求
    public function postXmlSSLCurl($xml,$url,$second=30)
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch,CURLOPT_HEADER,FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
        //设置证书
        //使用证书：cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT, ROOT_PATH.'extend/wxpay/cert/apiclient_cert.pem');
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,ROOT_PATH.'extend/wxpay/cert/apiclient_key.pem');
        //post提交方式
        curl_setopt($ch,CURLOPT_POST, true);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
        $data = curl_exec($ch);
        
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        }
        else {
            $error = curl_errno($ch);
			echo "curl出错，错误码:$error"."<br>"; 
			echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
			curl_close($ch);
            return false;
        }
    }
}

?>